package com.zoke.nebbox.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.zoke.neb.avatar.LogUtil;
import com.zoke.neb.avatar.api.NebAvatar;
import com.zoke.neb.avatar.http.SmartCallback;
import com.zoke.nebbox.Conf;
import com.zoke.nebbox.R;
import com.zoke.nebbox.base.BaseActivity;
import com.zoke.nebbox.dialog.AppLoading;
import com.zoke.nebbox.fragment.MainF;
import com.zoke.nebbox.fragment.MineF;
import com.zoke.nebbox.model.Result;
import com.zoke.nebbox.tools.PersistTool;
import com.zoke.nebbox.tools.TintManager;
import com.zoke.nebbox.tools.Util;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {


    private MainF mainF;
    private MineF mineF;

    @ViewInject(R.id.iv_main)
    ImageView iv_main;
    @ViewInject(R.id.iv_mine)
    ImageView iv_mine;
    @ViewInject(R.id.tv_main)
    TextView tv_main;
    @ViewInject(R.id.tv_mine)
    TextView tv_mine;

    private AppLoading loading;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    loading.dismiss();
                    Toast.makeText(MainActivity.this, "交易成功，数据存储成功", Toast.LENGTH_LONG).show();
                    loading.setTips("上传中");
                    if (mainF != null) mainF.onRefresh();
                    if (mineF != null) mineF.onRefresh();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loading = new AppLoading(this, "上传中");
        itemFragment(R.id.ll_main);
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.statusBarDarkFont(false).statusBarView(R.id.status).init();
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (mainF != null) transaction.hide(mainF);
        if (mineF != null) transaction.hide(mineF);
    }

    @Override
    protected void onResume() {
        //一定要掉这个 否则无法执行个别方法
        NebAvatar.getInstance().onResume(this);
        super.onResume();
    }

    @Event({R.id.ll_main, R.id.ll_mine, R.id.iv_scan})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_main:
                itemFragment(R.id.ll_main);
                mTitleBar.setTitle(R.string.app_name);
                break;
            case R.id.ll_mine:
                String add = PersistTool.getString(Conf.KEY, "");
                if (TextUtils.isEmpty(add)) {
                    startActivity(new Intent(this, LoginActivity.class));
                    return;
                }
                itemFragment(R.id.ll_mine);
                mTitleBar.setTitle("我的文件");
                break;
            case R.id.iv_scan:
                String address = PersistTool.getString(Conf.KEY, "");
                if (TextUtils.isEmpty(address)) {
                    startActivity(new Intent(this, LoginActivity.class));
                    return;
                }
                AndPermission.with(this)
                        .runtime()
                        .permission(Permission.Group.STORAGE)
                        .onGranted(permissions -> {
                            // Storage permission are allowed.
                            pickFile();
                        })
                        .onDenied(permissions -> {
                            // Storage permission are not allowed.
                            Toast.makeText(MainActivity.this, "权限被禁用，该功能将无法使用", Toast.LENGTH_LONG).show();
                        })
                        .start();

                break;
        }
    }

    //选择文件
    private void pickFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 1);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 1) {
                Uri uri = data.getData();
                String path;
                //使用第三方应用打开
                if ("file".equalsIgnoreCase(uri.getScheme())) {
                    path = uri.getPath();
                } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                    path = getPath(MainActivity.this, uri);
                } else {
                    path = getRealPathFromURI(uri);
                }
                postFile(path);
            }
        }
    }


    public String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            ;
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
            cursor.close();
        }
        return res;
    }

    /**
     * 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
     */
    @SuppressLint("NewApi")
    public String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


    private void postFile(String path) {
        LogUtil.e(path);
        NebAvatar.getInstance().postImage(path, new SmartCallback() {
            @Override
            public void onStart() {
                loading.show();
            }

            @Override
            public void onSuccess(final String response) {
                runOnUiThread(() -> {
                    LogUtil.e("response =" + response);
                    loading.dismiss();
                    Result res = new Gson().fromJson(response, Result.class);
                    if (res != null && res.code == 0 && res.data != null) {
                        PersistTool.saveString(Conf.KEY, res.data.from);
                        Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_LONG).show();
                        loading.setCancelable(true);
                        loading.show("交易pending请稍后…");
                        handler.sendEmptyMessageDelayed(1, 15000);
                    }
                });
            }

            @Override
            public void onError(final String error) {
                runOnUiThread(() -> {
                    LogUtil.e("error =" + error);
                    loading.dismiss();
                    Toast.makeText(MainActivity.this, "上传失败：" + error, Toast.LENGTH_LONG).show();
                });
            }
        });
    }


    public void itemFragment(int id) {
        //重置选项+隐藏所有Fragment
        item(id);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        hideFragments(transaction);
        switch (id) {
            case R.id.ll_main:
                if (mainF == null) {
                    mainF = new MainF();
                    transaction.add(R.id.container, mainF);
                } else {
                    transaction.show(mainF);
                }
                break;
            case R.id.ll_mine:
                if (mineF == null) {
                    mineF = new MineF();
                    transaction.add(R.id.container, mineF);
                } else {
                    transaction.show(mineF);
                }
                break;
        }
        transaction.commit();
    }


    private void item(int id) {
        TintManager.setTint(iv_main, getResources().getColor(id == R.id.ll_main ? R.color.baseColor : R.color.text_hint));
        TintManager.setTint(iv_mine, getResources().getColor(id == R.id.ll_mine ? R.color.baseColor : R.color.text_hint));
        tv_main.setSelected(id == R.id.ll_main);
        tv_mine.setSelected(id == R.id.ll_mine);
    }

}
